const Product = require('../modules/product');

exports.getProductList = (req, res, next) => {
    Product.fetchAll()
    .then(products => {
        res.render('admin/product-list', {
            prods: products,
            path: '/admin/product-list',
            pageTitle: '管理产品'
        })
    })
    .catch(err => console.log(err))
}
exports.getEditProduct = (req, res, next) => {
    const prodId = req.params.prodId;
    Product.findById(prodId)
    .then(product => {
        res.render('admin/edit-product', {
            product: product || {},
            pageTitle: '添加产品', 
            path: '/admin/add-product'
        });
    })
}

exports.postEditProduct = (req, res, next) => {
    const { id, title, imageUrl, price, description } = req.body;
    const product = new Product(id, title, imageUrl, price, description);
    product.save()
    .then(result => {
        res.redirect('/admin/product-list');
    })
    .catch(err => console.log(err))
}

exports.postDeleteProduct = (req, res, next) => {
    const prodId = req.body.prodId;
    Product.delById(prodId)
    .then(result => {
        res.redirect('/admin/product-list');
    })
    .catch(err => console.log(err))
}